package com.solution.common.utils.httpsclient;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.solution.common.utils.string.StringUtil;

/**
 * Https请求工具类
 * @author llp
 * @date 2017/5/6 11:56
 */
public class HttpsClient {
	private static SSLContext sslContext;
	private static X509TrustManager tm;
	private static HttpClient httpClient;

	static {
		try {
			// 初始化SSL上下文环境
			sslContext = SSLContext.getInstance("TLS");
			// 证书信任验证管理器
			tm = new MyX509TrustManager();
			sslContext.init(null, new TrustManager[] { tm },new SecureRandom());
			httpClient = HttpClients.custom()
						.setSSLHostnameVerifier(new MyVerifyHostname())
						.setSSLContext(sslContext).build();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * http 访问方法
	 * @param host 主机地址
	 * @param port 端口号
	 * @param url 请求路径
	 * @param requestData 数据
	 * @return
	 * @throws Exception
	 * @author chenl
	 * @date 2017年5月18日 上午9:41:49
	 */
	public static String doPostHttp(String host, Integer port, String url, String requestData) throws IOException, HttpException {
		org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
		PostMethod post = new PostMethod("http://"+host+"/"+url);
		post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		if (StringUtil.isNotNull("requestData")) {
			NameValuePair[] param = { new NameValuePair("requestData", URLEncoder.encode(requestData,"UTF-8"))};
			post.setRequestBody(param);
		} else {
			post.setRequestBody(requestData);
		}
		post.getParams().setContentCharset("utf-8");
		String respStr = "";
		client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
		client.executeMethod(post);
		respStr = URLDecoder.decode(post.getResponseBodyAsString(),"UTF-8");
		return respStr;
	}
	
	/**
	 * https 访问方法,使用URL编码格式
	 * @param host 主机地址
	 * @param port 端口号
	 * @param url 请求路径
	 * @param requestData 数据
	 * @return 返回结果
	 * @throws Exception
	 * @author xkl
	 * @date 2017年5月20日 上午10:23:17
	 */
	public static String doPost(String host, Integer port, String url, String requestData) throws Exception {
		URI uri = new URIBuilder()
				.setPath(url)
				.setScheme("https")
				.setHost(host)
//				.setPort(port)
				.setParameter("requestData",URLEncoder.encode(requestData,"UTF-8"))
				.build();
		HttpPost httpPost = new HttpPost(uri);
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity httpEntity = response.getEntity();
		httpEntity = new BufferedHttpEntity(httpEntity);
		String resultString = URLDecoder.decode(EntityUtils.toString(httpEntity), "UTF-8");
		return resultString;
	}
	
	public static String handRequest(String url) throws Exception {

		URI uri = new URIBuilder().setScheme("https")
				.setHost("dev.zhaiugo.com")
				//.setPort(443)
				.setPath(url)
				.setParameter("requestData", "{'phoneNumber':'13951843079','password':'123456'}")
				.build();
		
		HttpPost httpPost = new HttpPost(uri);
		httpPost.setHeader("deviceType","android");
		httpPost.setHeader("deviceID","1ff39bda2c508df049bc3996118fda40");
		httpPost.setHeader("token","e0693994-f376-401f-8a8b-5b026693566e");
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity httpEntity = response.getEntity();
		httpEntity = new BufferedHttpEntity(httpEntity);
		String resultString = EntityUtils.toString(httpEntity);
		return resultString;
	}

	public static void main(String[] args) {
		try {
			String resultString = handRequest("/zhaiugo-dl-web/inter/salesman/salesmanLoginInfo");
			
			System.out.println(resultString);
		} catch (URISyntaxException | IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}